<?php

namespace app\erp\controller;

use app\admin\model\Customeraddress;
use app\admin\model\Porder;
use app\admin\model\Synlogs;
use think\Log;

class Purorder extends Base
{
    public function __construct($starttime, $endtime,$client_id,$client_secret,$account_id,$user_name)
    {
        parent::__construct($client_id, $client_secret,$account_id,$user_name);

        $this->starttime = $starttime;
        $this->endtime   = $endtime;
    }
    public function run($forg_fnumber,$forig_id,$page,$pageSize,$uuid)
    {

        $res = $this->getBizpersonGroupPage($forg_fnumber,$page,$pageSize,$uuid);

        if($res['code'] === 1)
        {
            $response = $this->insertDataAndUpdateSuper($res['data'], $forig_id,$uuid);

            if($response)
            {
                Synlogs::where('id',$uuid)->update([
                    'fk_bdl_successnums' => $response['total'],
                    'fk_bdl_status'      => "true",
                    'fk_bdl_endtime'     => date("Y-m-d H:i:s"),
                ]);
                Log::info('订单同步成功,'. "时间：".date('Y-m-d H:i:s') . "组织编码："  . $forg_fnumber . "参数：" . json_encode($res['data']));

                $this->getCount();
                return "组织编码".$forg_fnumber . ':本次成功同步条数' . $response['total'];

            }
        }elseif ($res['code'] === 2) {
            Synlogs::where('id',$uuid)->update([
                'fk_bdl_successnums' => 0,
                'fk_bdl_status'      => "true",
                'fk_bdl_endtime'     => date("Y-m-d H:i:s"),
            ]);
            $this->getCount();
            return "组织编码".$forg_fnumber . ':本次成功同步条数0';

        }

    }

    private function getBizpersonGroupPage($createorg_number, $pageNo, $pageSize,$uuid)
    {
        $method  = "v2/bdl/bdl_sal/bdl_sal_order/queryOrder";

        $fullurl = $this->url . $method;

        Synlogs::where('id',$uuid)->update([
            'fk_bdl_url'        => $fullurl,

        ]);
        $response_data = [
            'data'      => [
                'starttime'             => $this->starttime,
                'endtime'               => $this->endtime,
                'org_number'            => $createorg_number,
                'bdl_bd_datacenter'     => $this->account_id,
            ],
            'pageNo'    => $pageNo,
            'pageSize'  => $pageSize,
        ];


        $this->curl->setHeader("Content-Type", "application/json");
        $this->curl->setHeader("accesstoken", $this->getToken());
        $this->curl->setHeader("Idempotency-Key", uuid());

        $res = $this->curl->post($fullurl, json_encode($response_data));


        if ($res && is_object($res) && $res->status == 1)
        {
            if($res->data->totalCount > 0){

                return [
                    'data' => $res->data->rows,
                    'code'  => 1

                ];
            }else{
                return [
                    'code'  => 2,
                ];
            }

        }else{
            if(strlen($res->message) > 255)
            {
//                $res->message = substr($res->message,0,155);

                return $this->error('aaaaaaaa'  . request()->action() . $res->message);

            }
            if(property_exists($res,'errorCode') && $res->errorCode == 404)
            {
                return $this->error('aaaaaaaa'  . request()->action() . $res->message);
            }

            Synlogs::where('id',$uuid)->update([
                'fk_bdl_exceptionmsg'   => $res->message,
                'fk_bdl_status'         => "false",
            ]);
            Log::info('订单同步失败,'  . "时间：".date('Y-m-d H:i:s') . "组织编码："  . $createorg_number . "参数：" . json_encode($response_data));
            return [
                'data' => false,
                'code'  => 0
            ];
        }


    }

    private function insertDataAndUpdateSuper($data, $forgid,$uuid)
    {
        $count = 0;

        if(!empty($data))
        {
            try {
                // 组装 data 并插入
                foreach ($data as $k => $v)
                {

                    //判断是否已经存在 订单号 组织 数据中心
                    $isExist = \app\admin\model\Porder::where('fk_bdl_erpbillno', $v->billno)->where('forgid',$forgid)->where('fk_bdl_bd_datacenter',$this->account_id)->find();

                    //组装数据

                    $insertData = [
                        'fk_bdl_createtime'                 => $v->createtime,
                        'fk_bdl_modifytime'                 => $v->modifytime,
                        'fk_bdl_allamount'                  => $v->bdl_allamounth,
                        'forgid'                            => $forgid,
                        'fk_bdl_bd_datacenter'              => $this->account_id,
                    ];

                    property_exists($v,'bdl_bd_customer_number')    ?    $insertData['fk_bdl_bd_customer']       =       $this->getCustomerID($v->bdl_bd_customer_number,$forgid,$this->account_id)    :               '';
                    property_exists($v,'addressNum')                ?    $insertData['fk_bdl_bd_useraddress']    =       $this->getCustomerAddress($v->addressNum,$forgid,$this->account_id)           :               '';
                    property_exists($v,'bdl_bd_carinfo_number')     ?    $insertData['fk_bdl_bd_carinfo']        =       $this->getCarinfoID($v->bdl_bd_carinfo_number,$forgid,$this->account_id)      :               '';
                    property_exists($v,'billno')                    ?    $insertData['fk_bdl_erpbillno']         =       $v->billno                                          :               '';
                    property_exists($v,'bdl_orderstatus')           ?    $insertData['fk_bdl_orderstatus']       =       $v->bdl_orderstatus                                 :               '';
                    property_exists($v,'bdl_signfortime')                   ?    $insertData['fk_bdl_signtime']          =       $v->bdl_signfortime                                       :               '';
                    property_exists($v,'auditdate')                     ?    $insertData['fk_bdl_ordertime']         =       $v->auditdate                                 :               '';
                    property_exists($v,'bdl_deliverytime')          ?    $insertData['fk_bdl_planreceivetime']   =       $v->bdl_deliverytime                                :               '';
                    property_exists($v,'bdl_planshiptime')          ?    $insertData['fk_bdl_planshiptime']      =       $v->bdl_planshiptime                                :               '';
                    property_exists($v,'bdl_entry')                     ?   $insertData['fk_bdl_orderjsondata']    =       json_encode($v->bdl_entry)                                :               '';
                    property_exists($v,'bdl_deliverask')                    ?   $insertData['fk_bdl_comment']    =       json_encode($v->bdl_deliverask)                                :               '';
                    property_exists($v,'returntime')                    ?   $insertData['fk_bdl_returntime']    =       $v->returntime                                :               '';
                    property_exists($v,'bdl_date')                    ?   $insertData['fk_bdl_date']    =       $v->bdl_date                                :               '';




                    if(!empty($isExist))
                    {
                        \app\admin\model\Porder::where('id',$isExist['id'])->update($insertData);
                    }else{
                        \app\admin\model\Porder::create($insertData);

//                    $stock = $v->bdl_entry;
                        //同步库存
//                    if($res)
//                    {
//                        if($this->account_id === '1833526278980894720')
//                        {
//                            pdump($this->syncStockForJin($res['id'],$stock));
//                        }else{
//                            $this->syncStockForOther($res['id'],$stock);
//                        }
//                    }
                    }

                    $count++;

                }
            }catch (\Exception $e)
            {
                Synlogs::where('id',$uuid)->update([
                    'fk_bdl_exceptionmsg' => $e->getMessage(),
                    'fk_bdl_status'         => "false",
                ]);
                Log::error('订单同步失败,'. $e->getMessage() . "时间：".date('Y-m-d H:i:s') . "组织编码："  . $forgid . "参数：" . json_encode($data));

                $this->error($e->getMessage());

            }
        }
        return [
            'code'      =>1,
            'total'     => $count,
        ];

    }



    private function syncStockForJin($id,$stock_data)
    {

    }
    private function syncStockForOther($id,$stock_data)
    {

    }

    private function getCustomerID($customer=null,$forgid=null,$account_id=null)
    {
        $id = '';
        if(!empty($customer) && !empty($forgid) && !empty($account_id))
        {
                $id = \app\admin\model\Customer::where('fnumber',$customer)->where('fk_bdl_bd_datacenter',$account_id)->value('id');
        }

        return $id;
    }
    private function getCarinfoID($CarinfoID=null,$forgid=null,$account_id=null)
    {
        $id = '';
        if(!empty($CarinfoID)  && !empty($forgid) && !empty($account_id))
        {
            $id = \app\admin\model\Carinfo::where('fnumber',$CarinfoID)->where('fk_bdl_bd_datacenter',$account_id)->value('id');
        }
        return $id;
    }
    private function getCustomerAddress($CustomerAddress=null,$forgid=null,$account_id=null)
    {
        $id = '';
        if(!empty($CustomerAddress)  && !empty($forgid) && !empty($account_id))
        {
            $id = Customeraddress::where('fnumber',$CustomerAddress)->where('fk_bdl_bd_datacenter',$account_id)->value('id');
        }
        return $id;
    }

    public function getCount()
    {
        $data = Porder::whereNull('fk_bdl_allqty')->whereNotNull('fk_bdl_orderjsondata')->select();
        foreach ($data as $k => $v)
        {
            $fk_bdl_orderjsondata = json_decode($v['fk_bdl_orderjsondata'],true);
            if(!empty($fk_bdl_orderjsondata))
            {
                $fk_bdl_allqty = [];
                foreach ($fk_bdl_orderjsondata as $key => $value)
                {
                    $fk_bdl_allqty[] = floatval($value['bdl_qty']);
                }

                Porder::where('id',$v['id'])->update(['fk_bdl_allqty' => array_sum($fk_bdl_allqty)]);
            }

        }
    }






}